#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'HaiFeng'
__mtime__ = '2016/9/23'
"""
import _thread

from py_at.Tool import *
from py_at.adapters.QuoteAdapter import *
from py_at.at_struct import *
from py_ctp.src.quote import *

class CtpQuote(QuoteAdapter):
    """"""

    def __init__(self):
        super().__init__()
        self.q = Quote()

    def ReqConnect(self, pAddress=''):
        self.q.CreateApi()
        spi = self.q.CreateSpi()
        self.q.RegisterSpi(spi)

        self.q.OnFrontConnected = self.__OnFrontConnected
        self.q.OnRspUserLogin = self.__OnRspUserLogin
        self.q.OnRtnDepthMarketData = self.__OnRtnDepthMarketData
        self.q.OnRspSubMarketData = self.__OnRspSubMarketData
        self.q.OnFrontDisconnected = self.__OnFrontDisconnected
        self.q.RegCB()

        self.q.RegisterFront(pAddress)
        self.q.Init()

    def ReqUserLogin(self, user='', pwd='', broker=''):
        self.q.ReqUserLogin(
            BrokerID=broker,
            UserID=user,
            Password=pwd
        )

    def ReqSubscribeMarketData(self, pInstrument=''):
        print("订阅")
        self.q.SubscribeMarketData(pInstrument)

    def __OnFrontConnected(self):
        """"""
        _thread.start_new_thread(self.OnFrontConnected, ())

    def __OnRspUserLogin(self, pRspUserLogin=CThostFtdcRspUserLoginField, pRspInfo=CThostFtdcRspInfoField,
                         nRequestID=int, bIsLast=bool):
        """"""
        info = InfoField()
        info.ErrorID = pRspInfo.getErrorID()
        info.ErrorMsg = pRspInfo.getErrorMsg()
        _thread.start_new_thread(self.OnRspUserLogin, (info,))

    def __OnRtnDepthMarketData(self, pDepthMarketData=CThostFtdcDepthMarketDataField):
        """"""
        tick = Tick()
        #暂时不用都不加载了 增加实盘速度
        #tick.AskPrice = pDepthMarketData.getAskPrice1()
        #tick.AskVolume = pDepthMarketData.getAskVolume1()
        #tick.AveragePrice = pDepthMarketData.getAveragePrice()
        #tick.BidPrice = pDepthMarketData.getBidPrice1()
        #tick.BidVolume = pDepthMarketData.getBidVolume1()
        tick.Instrument = pDepthMarketData.getInstrumentID()
        tick.LastPrice = pDepthMarketData.getLastPrice()
        tick.OpenInterest = pDepthMarketData.getOpenInterest()
        tick.Volume = pDepthMarketData.getVolume()
        tick.UpperLimitPrice = pDepthMarketData.getUpperLimitPrice()
        tick.LowerLimitPrice = pDepthMarketData.getLowerLimitPrice()
        tick.AskPrice = pDepthMarketData.getAskPrice1()
        tick.BidPrice = pDepthMarketData.getBidPrice1()

        tick.TradingDay = pDepthMarketData.getTradingDay() #增加交易日期
        #day = pDepthMarketData.getTradingDay()  没有理由使用交易日期
        day = pDepthMarketData.getActionDay()  #应该是用发生日期  2017-9-4更改
        str = day + ' ' + pDepthMarketData.getUpdateTime()
        if day == None or day == ' ':
            str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        #tick.UpdateTime = time.strptime(str, '%Y%m%d %H:%M:%S')
        tick.Strtime = str   #字符串格式
        tick.UpdateTime = customized_parse(str)  #工具类函数

        # if self.DicTick.get(tick.Instrument):
        #     self.DicTick[tick.Instrument].append([str,tick.LastPrice])
        # else:
        #     self.DicTick[tick.Instrument]=[[str,tick.LastPrice]]
        #_thread.start_new_thread(self.OnRtnTick, (tick,))
        self.OnRtnTick(tick)

    def __OnRspSubMarketData(self, pSpecificInstrument=CThostFtdcSpecificInstrumentField, pRspInfo=CThostFtdcRspInfoField,
                           nRequestID=int, bIsLast=bool):

        self.OnRspSubMarketData(pRspInfo,bIsLast)

    def __OnFrontDisconnected(self, nReason):
        self.OnFrontDisConnected(nReason)


    def OnFrontDisConnected(self, error=0):
        """"""
        pass

    def OnRspUserLogin(self, info=InfoField):
        """"""
        pass

    # ----------------------------------------------------------------------
    def OnRtnTick(self, field=Tick):
        """"""
        pass

    #-----------------------------------------------------------------------
    def OnRspSubMarketData(self,pRspInfo,bIsLast):
        """"""
        pass
